package com.humh.stock.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.humh.stock.common.CommonResult;
import com.humh.stock.common.HttpClientUtils;
import com.humh.stock.controller.req.StockReq;
import com.humh.stock.controller.res.StockRes;
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>库存接口</p>
 * Create by hgx61 at 2024/10/18
 */
@RestController
@RequestMapping("/stocks")
public class StockController {

  private static final String URL_CHECK_TOKEN = "http://localhost:8082/tokens/checkToken";  // 验证token 是否存在


  /**
   * 扣减库存量
   * @param token
   * @param stockReq
   * @return
   */
  @PostMapping
  public CommonResult<StockRes> deductionOfInventory(@RequestHeader("token")String token,
      @RequestBody StockReq  stockReq) throws Exception {


    Map<String, String> params = new HashMap<>();
    params.put("token", token);

    // 访问certification-service 的TokenController.verifyToken() 验证token 是否存在,存在则继续处理创建订单的请求，反之则返回错误信息
    JsonNode tokenJsonNode = HttpClientUtils.sendGet(URL_CHECK_TOKEN, null, params);
    // 验证token
    if (!CommonResult.isSuccess(tokenJsonNode.get("code").asInt())) { // token 不存在
      return CommonResult.error(tokenJsonNode.get("code").asInt(), tokenJsonNode.get("msg").asText());
    }


    StockRes stockRes = new StockRes();
    stockRes.setNum(stockReq.getNum());
    stockRes.setProductCode(stockReq.getProductCode());
    stockRes.setStatus("成功扣减库存量");

    return CommonResult.success(stockRes);

  }

}
